//
//  AddOilViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/30.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit

class AddOilViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    private var img1url: String?
    private var img2url: String?
    
    @IBOutlet weak var imgButton1: UIButton!
    @IBOutlet weak var imgButton2: UIButton!
    
    private var currentImg = 1
    
    var orderId: String!
    
    var gasId: String?
    
    var oilMoney: Float = 100.00
    
    @IBOutlet weak var gasNameLabel: UILabel!
    @IBOutlet weak var oilMoneyLabel: UILabel!
    
    @IBOutlet weak var riseField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func photograph(_ sender: UIButton) {
        if sender == imgButton1 {
            currentImg = 1
        } else if sender == imgButton2 {
            currentImg = 2
        }
        
        #if DEBUG
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true
            picker.sourceType = .camera
            self.present(picker, animated: true, completion: nil)
        } else {
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                let picker = UIImagePickerController()
                picker.delegate = self
                picker.allowsEditing = true
                picker.sourceType = .photoLibrary
                self.present(picker, animated: true, completion: nil)
            } else {
                p("读取相册失败")
            }
        }
        #else
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true
            picker.sourceType = .camera
            present(picker, animated: true, completion: nil)
        } else {
            showError("不支持拍照")
        }
        #endif
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        DispatchQueue.global().async { [weak self] in
            if let self = self {
                let imgData = image.compress(maxSizeKBytes: kMaxSizeKBytes)
                DispatchQueue.main.async {
                    let file = HTTPRequest.File(data: imgData, name: "image_path", fileName: "file.jpg", mimeType: "image/jpg")
                    
                    JZLoading.showLoadingWith(toView: self.view)
                    File.upload(file: file, success: { data in
                        JZLoading.hideLoading()
                        if self.currentImg == 1 {
                            self.imgButton1.setImage(image, for: .normal)
                            self.img1url = data?.imagePath
                        } else if self.currentImg == 2 {
                            self.imgButton2.setImage(image, for: .normal)
                            self.img2url = data?.imagePath
                            self.imgButton2.setTitle(nil, for: .normal)
                        }
                    }) { error in
                        JZLoading.hideLoading()
                        self.showError(error)
                    }
                    self.dismiss(animated: true, completion: nil)
                }
            }
        }
    }
    
    @IBAction func addOil(_ sender: UIButton) {
        guard let orderId = orderId else {
            return
        }
        
        guard let gasId = self.gasId else {
            showError("请您选择加油站(1032)")
            return
        }
        
        guard let url1 = self.img1url else {
            showError("请您上传清晰仪表盘照片(1035)")
            return
        }
        
        guard let url2 = self.img2url else {
            showError("请您上传清晰加油小票照片(1036)")
            return
        }
        
        guard let rise = self.riseField.text else {
            showError("请您填写加油油量(1033)")
            return
        }
        
        guard let r = Float(rise) else {
            showError("油量输入有误，请您重新输入(1034)")
            return
        }
        
        if self.oilMoney == 100.00 && (r < 10 || r > 20) {
            showError("油量输入有误，请您重新输入(1034)")
            return
        }
        
        if oilMoney == 200.00 && (r < 20 || r > 40) {
            showError("油量输入有误，请您重新输入(1034)")
            return
        }
        
        alert(title: nil, message: "请您仔细核对，若发票抬头和税号有误，将无法完成审核返还。(1037)") { [weak self] in
            if let self = self {
                JZLoading.showLoadingWith(toView: self.view)
                Order.addOil(orderId: orderId,
                             gasId: gasId,
                             oilMoney: self.oilMoney,
                             location: self.userLocation,
                             rise: r,
                             oilImagePath: url1,
                             billImagePath: url2,
                             success: {
                                JZLoading.hideLoading()
                                XHProgressHUD.showSuccess("加油成功！")
                                self.navigationController?.popViewController(animated: true)
                }) { error in
                    JZLoading.hideLoading()
                    self.showError(error)
                }
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 1 {
            let sheet = UIAlertController(title: "选择金额", message: nil, preferredStyle: .actionSheet)
            
            let action1 = UIAlertAction(title: "100.00元", style: .default) { [weak self] action in
                self?.oilMoney = 100.00
                self?.oilMoneyLabel.text = "100.00元"
            }
            sheet.addAction(action1)
            
            let action2 = UIAlertAction(title: "200.00元", style: .default) { [weak self] action in
                self?.oilMoney = 200.00
                self?.oilMoneyLabel.text = "200.00元"
            }
            sheet.addAction(action2)
            
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            sheet.addAction(cancel)
            
            present(sheet, animated: true) {
                if let indexPath = tableView.indexPathForSelectedRow {
                    tableView.deselectRow(at: indexPath, animated: true)
                }
            }
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gasSegue" {
            guard let vc = segue.destination as? GasListViewController else {
                return
            }
            
            vc.delegate = self
        } else if segue.identifier == "webViewSegue" {
            guard let nav = segue.destination as? UINavigationController else {
                return
            }
            
            guard let vc = nav.viewControllers.first as? WebViewController else {
                return
            }
            
            vc.page = Page.server(.refuel)
        }
    }
}
